iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 22
1
自我挑戰組

原來電腦可以這樣用!? 果蠅也懂的程式語言教學系列 第 22

Day22-Python Line 整合應用2 -- Line 對話機器人II

  • 分享至 

  • xImage
  •  

我們需要一個伺服器來部屬我們的 Linebot 才能有不間斷的服務,但一般人家中不會有伺服器,也沒必要為了一個小服務去買虛擬主機,所以我們選用一個免費部屬服務,heroku


先到 https://www.heroku.com/ 註冊一個帳號並登入

https://ithelp.ithome.com.tw/upload/images/20191008/20120282q34KoT3yYY.jpg

點擊紅框內的 New 來建立一個新服務
https://ithelp.ithome.com.tw/upload/images/20191008/20120282pjsg52DwQi.jpg

輸入服務的名字,並選擇伺服器地區,我習慣選擇美國
https://ithelp.ithome.com.tw/upload/images/20191008/20120282BrxuyEp9Da.jpg

建立成功後頁面往下滑,我們會看到一些操作資訊,到這邊我們要安裝一個工具 Heroku CLI,到這個連結下載並安裝 https://devcenter.heroku.com/articles/heroku-cli#download-and-install

也可以透過 choco install heroku-cli 來安裝

https://ithelp.ithome.com.tw/upload/images/20191008/20120282i061JkB8JS.jpg


初始程式撰寫

我們先寫一個練習程式,讓 Line 對話機器人會重複你說的話,因為這個服務是建立在 HTTP 的基礎上,因此我們需要 HTTP 伺服器,剛好就可以用到前些日子介紹過的 Flask 來完成。

建立 requirements.txt 提供 heroku 雲端服務知道你部屬時需要安裝那些套件。

line-bot-sdk
flask

建立一個 app.py(程式碼來源:https://dotblogs.com.tw/funny_dotblog/2018/11/14/chatbot_python_3),將上一篇的 Access Token 填入 line_bot_api 變數,Channel Secret 填入 handler 變數中。

from flask import Flask, request, abort
from urllib.request import urlopen
#from oauth2client.service_account import ServiceAccountCredentials

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError,LineBotApiError
)

### Script start ###

from linebot.models import *

app = Flask(__name__)

# Channel Access Token
line_bot_api = "你的Channel access token"
# Channel Secret
handler = WebhookHandler('"你的Channel secret"')

# 監聽所有來自 / 的 Post Request
@app.route("/", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']
    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)
    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return 'OK'

# 處理訊息
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    print(event)
    reply_text =event.message.text

    message = TextSendMessage(reply_text)
    line_bot_api.reply_message(event.reply_token, message)

import os
if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

接著我們在 cmd 中執行 heroku login 來登入 heroku,它現在會自動跳轉到瀏覽器進行登入,很方便。
https://ithelp.ithome.com.tw/upload/images/20191008/20120282s343Si9KQW.jpg

進入專案目錄,初始化 git 儲存庫,這邊使用 git 版本管理的方式進行推送部屬,這部分我不詳細講,照著指令打即可,可興趣了解 git 的可以參考這裡。

git init
heroku git:remote -a ironman2019-test

再來連續執行以下指令,將我們的程式碼送到 heroku 去自動部屬。

git add .
git commit -am "first push."
git push heroku master

第一次他會出現這些部屬的 log

$ git push heroku master
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 8 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 1.12 KiB | 1.12 MiB/s, done.
Total 4 (delta 0), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.6.9
remote: -----> Installing pip
remote: -----> Installing SQLite3
remote: -----> Installing requirements with pip
remote:        Collecting line-bot-sdk (from -r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/ea/78/79f1b6a7ce1b10e262e3cd99d8b7801a735fb99e9c3df087558416c06051/line_bot_sdk-1.14.0-py2.py3-none-any.whl (52kB)
remote:        Collecting flask (from -r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 2))
remote:          Downloading https://files.pythonhosted.org/packages/9b/93/628509b8d5dc749656a9641f4caf13540e2cdec85276964ff8f43bbb1d3b/Flask-1.1.1-py2.py3-none-any.whl (94kB)
remote:        Collecting future (from line-bot-sdk->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/90/52/e20466b85000a181e1e144fd8305caf2cf475e2f9674e797b222f8105f5f/future-0.17.1.tar.gz (829kB)
remote:        Collecting requests>=2.0 (from line-bot-sdk->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/51/bd/23c926cd341ea6b7dd0b2a00aba99ae0f828be89d72b2190f27c11d4b7fb/requests-2.22.0-py2.py3-none-any.whl (57kB)
remote:        Collecting itsdangerous>=0.24 (from flask->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 2))
remote:          Downloading https://files.pythonhosted.org/packages/76/ae/44b03b253d6fade317f32c24d100b3b35c2239807046a4c953c7b89fa49e/itsdangerous-1.1.0-py2.py3-none-any.whl
remote:        Collecting Jinja2>=2.10.1 (from flask->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 2))
remote:          Downloading https://files.pythonhosted.org/packages/65/e0/eb35e762802015cab1ccee04e8a277b03f1d8e53da3ec3106882ec42558b/Jinja2-2.10.3-py2.py3-none-any.whl (125kB)
remote:        Collecting click>=5.1 (from flask->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 2))
remote:          Downloading https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl (81kB)
remote:        Collecting Werkzeug>=0.15 (from flask->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 2))
remote:          Downloading https://files.pythonhosted.org/packages/ce/42/3aeda98f96e85fd26180534d36570e4d18108d62ae36f87694b476b83d6f/Werkzeug-0.16.0-py2.py3-none-any.whl (327kB)
remote:        Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 (from requests>=2.0->line-bot-sdk->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/e0/da/55f51ea951e1b7c63a579c09dd7db825bb730ec1fe9c0180fc77bfb31448/urllib3-1.25.6-py2.py3-none-any.whl (125kB)
remote:        Collecting idna<2.9,>=2.5 (from requests>=2.0->line-bot-sdk->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl (58kB)
remote:        Collecting chardet<3.1.0,>=3.0.2 (from requests>=2.0->line-bot-sdk->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB)
remote:        Collecting certifi>=2017.4.17 (from requests>=2.0->line-bot-sdk->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/18/b0/8146a4f8dd402f60744fa380bc73ca47303cccf8b9190fd16a827281eac2/certifi-2019.9.11-py2.py3-none-any.whl (154kB)
remote:        Collecting MarkupSafe>=0.23 (from Jinja2>=2.10.1->flask->-r /tmp/build_be892a29d7dfc0edd6e025a28a31320d/requirements.txt (line 2))
remote:          Downloading https://files.pythonhosted.org/packages/b2/5f/23e0023be6bb885d00ffbefad2942bc51a620328ee910f64abe5a8d18dd1/MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
remote:        Installing collected packages: future, urllib3, idna, chardet, certifi, requests, line-bot-sdk, itsdangerous, MarkupSafe, Jinja2, click, Werkzeug, flask
remote:          Running setup.py install for future: started
remote:            Running setup.py install for future: finished with status 'done'
remote:        Successfully installed Jinja2-2.10.3 MarkupSafe-1.1.1 Werkzeug-0.16.0 certifi-2019.9.11 chardet-3.0.4 click-7.0 flask-1.1.1 future-0.17.1 idna-2.8 itsdangerous-1.1.0 line-bot-sdk-1.14.0 requests-2.22.0 urllib3-1.25.6
remote:
remote: -----> Discovering process types
remote:        Procfile declares types -> (none)
remote:
remote: -----> Compressing...
remote:        Done: 46.6M
remote: -----> Launching...
remote:        Released v3
remote:        https://ironman2019-test.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/ironman2019-test.git
 * [new branch]      master -> master

接下來到 Line developer 裡面設定 webhook heroku的服務網址,並且驗證
https://ithelp.ithome.com.tw/upload/images/20191008/20120282ZvAr7ilyQT.jpg

https://ithelp.ithome.com.tw/upload/images/20191008/20120282qrQA3fBnHm.jpg

最後再加入 line bot 好友,發送訊息給他測試看看有沒有成功~


參考資料
https://dotblogs.com.tw/funny_dotblog/2018/11/14/chatbot_python_3
https://github.com/line/line-bot-sdk-python


上一篇
Day21-Python Line 整合應用2 -- Line 對話機器人
下一篇
Day23-Python Line 整合應用2 -- Line 對話機器人III
系列文
原來電腦可以這樣用!? 果蠅也懂的程式語言教學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言